package org.springblade.modules.admin.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.entity.ElevatorPrincipalDept;
import org.springblade.modules.admin.entity.ElevatorPrincipalUser;
import org.springblade.modules.admin.service.*;
import org.springblade.modules.admin.vo.*;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import org.springblade.modules.admin.mapper.MaintainBusinessLogMapper;
import org.springblade.modules.admin.entity.MaintainBusinessLog;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author Sharry
 * @since 2023/2/9 17:43
 */


@Service
public class MaintainBusinessLogServiceImpl extends BaseServiceImpl<MaintainBusinessLogMapper, MaintainBusinessLog> implements MaintainBusinessLogService{

	@Autowired
	@Lazy
	private IUserService userService;

	@Autowired
	@Lazy
	private IElevatorDetailService elevatorDetailService;

	@Autowired
	@Lazy
	private BuildingService buildingService;

	@Autowired
	@Lazy
	private ElevatorService elevatorService;

	@Autowired
	@Lazy
	private ElevatorPrincipalDeptService elevatorPrincipalDeptService;

	@Autowired
	@Lazy
	private IDeptService deptService;

	@Autowired
	@Lazy
	private ElevatorPrincipalUserService elevatorPrincipalUserService;


	@Override
	public IPage<MaintainBusinessLogVO> selectLogPages(IPage<MaintainBusinessLogVO> page, Long paramKey, Integer type, String beginTime, String endTime) {
		//日期参数校验
		DateTime parseBegin = DateUtil.parse(beginTime);
		DateTime parseEnd = DateUtil.parse(endTime);
		if(ObjectUtil.isNotNull(parseBegin) && ObjectUtil.isNotNull(parseEnd)){
			if(parseBegin.getTime()>parseEnd.getTime()){
				throw new ServiceException("查询失败！开始时间必须早于结束时间！");
			}
		}
		IPage<MaintainBusinessLogVO> resultPage = baseMapper.selectBusinessLogPages(page, paramKey, type, beginTime, endTime);
		//获取page里userId 并赋真实姓名
		List<MaintainBusinessLogVO> records = resultPage.getRecords();
		for(MaintainBusinessLogVO vos : records){
			Long createUser = vos.getCreateUser();
			String realName = userService.getById(createUser).getRealName();
			vos.setUserRealName(realName);
		}
		//修改后的数据返回给分页信息
		resultPage.setRecords(records);
		return resultPage;
	}

	@Override
	public ElevatorRelationDetailVO getRelationDetail(Long elevatorId) {
		//参数传入完整校验
		if(ObjectUtil.isNull(elevatorId)){
			throw new ServiceException("获取电梯信息失败，请联系系统管理员！");
		}
		//定义接收VO
		ElevatorRelationDetailVO result = elevatorService.selectElevatorRelationDetail(elevatorId);

		//获取所属梯组
		ElevatorPrincipalDept principalDept = elevatorPrincipalDeptService.getOne(new LambdaQueryWrapper<ElevatorPrincipalDept>()
			.eq(ElevatorPrincipalDept::getElevatorId, elevatorId));
		if(ObjectUtil.isNull(principalDept)){
			result.setGroup(null);
		}else{
			Long deptId = principalDept.getDeptId();
			if(null == deptId){
				result.setGroup(null);
			}else {
				//获取所属梯组完整id 数组
				String ancestors = deptService.getById(deptId).getAncestors();
				//当祖级列表仅为0时
				if ("0".equals(ancestors.trim())) {
					result.setGroup(deptService.getById(deptId).getDeptName());
				} else {
					String[] ids = ancestors.split(",");
					ids = Arrays.copyOf(ids, ids.length + 1);
					ids[ids.length - 1] = deptId.toString();
					//根据 id 数组获取所属梯组中文名并拼接
					String[] deptNames = new String[ids.length - 1];
					for (int i = 1; i < ids.length; i++) {
						Long tempId = Long.parseLong(ids[i]);
						Dept getById = deptService.getById(tempId);
						deptNames[i - 1] = getById.getDeptName();
					}
					String group = String.join("/", deptNames);
					result.setGroup(group);
				}
			}
		}
		//获取责任人
		List<ElevatorPrincipalUser> userList = elevatorPrincipalUserService.list(new LambdaQueryWrapper<ElevatorPrincipalUser>()
			.eq(ElevatorPrincipalUser::getElevatorId, elevatorId));
		if(Func.isEmpty(userList)){
			result.setUsers(null);
		}else{
			List<String> userNameList = new ArrayList<>();
			for(ElevatorPrincipalUser elevatorPrincipalUser : userList){
				User user = userService.getById(elevatorPrincipalUser.getUserId());
				userNameList.add(user.getRealName());
			}
			String users = String.join(",", userNameList);
			result.setUsers(users);
		}
		return result;
	}


	@TenantIgnore
	@Override
	public IPage<ElevatorSignLogVO> getSingleSignLog(Long elevatorId,String beginTime, String endTime, IPage<ElevatorSignLogVO> page,String tenantId) {
		IPage<ElevatorSignLogVO> pages = baseMapper.getSingleSignLog(elevatorId,  beginTime,  endTime, page,tenantId);
		return pages;
	}

	@Override
	public List<MaintainBusinessLog> listNewestGroupByElevator(List<Long> elevatorIds, int type) {
		return baseMapper.listNewestGroupByElevator(elevatorIds,type);
	}

	/**
	 * 根据电梯id查询电梯维修日志
	 * @param elevatorId 电梯id
	 * @param beginTime 开始时间
	 * @param endTime 结束时间
	 * @param page 分页参数
	 * @return 维修日志
	 */
	@Override
	public IPage<ElevatorRepairLogVO> getSingleRepairLog(
		Long elevatorId,
		@DateTimeFormat(pattern="yyyy-mm-dd HH:mm:ss") Date beginTime,
		@DateTimeFormat(pattern="yyyy-mm-dd HH:mm:ss") Date endTime,
		IPage<ElevatorRepairLogVO> page
	) {
		// 0. 数据校验、查询数据
		if (Func.isEmpty(elevatorId) || Func.isEmpty(page)) {
			throw new ServiceException("参数不能为空");
		}
		IPage<ElevatorRepairLogVO> pages = baseMapper.getSingleRepairLog(page, elevatorId, beginTime, endTime);
		// 1. 数据处理：补充停梯描述、报障描述
		List<ElevatorRepairLogVO> records = pages.getRecords();
		for (ElevatorRepairLogVO record : records) {
			record.setReportStatus(
				Func.isNull(record.getElevatorStop()) ? "停梯" :
				new Integer("1").equals(record.getElevatorStop()) ? "正常运行" : "停梯"
			);
			// Switch case 语句赋值报障渠道描述
			switch (Func.toInt(record.getPlanFrom())) {
				case 1:
					record.setReportChannel("物业端报障");
					break;
				case 2:
					record.setReportChannel("微信群报障");
					break;
				case 3:
					record.setReportChannel("服务电话报障");
					break;
				case 4:
					record.setReportChannel("系统派单");
					break;
				case 5:
					record.setReportChannel("维保端报障");
					break;
				case 6:
					record.setReportChannel("游客报障");
					break;
				case 7:
					record.setReportChannel("web端报障");
					break;
				case 8:
					record.setReportChannel("梯联网");
					break;
				default:
					record.setReportChannel("无报障渠道记录");
					break;
			}
		}
		// 2. 返回数据
		pages.setRecords(records);
		return pages;
	}

	@Override
	public IPage<ElevatorRescueLogVO> getSingleRescueLog(
		Long elevatorId,
		@DateTimeFormat(pattern="yyyy-mm-dd HH:mm:ss") Date beginTime,
		@DateTimeFormat(pattern="yyyy-mm-dd HH:mm:ss") Date endTime,
		IPage<Object> page) {
		// 0. 数据校验、查询数据
		if (Func.isEmpty(elevatorId) || Func.isEmpty(page)) {
			throw new ServiceException("参数不能为空");
		}
		// 1. 查询数据 补充困人类型描述描述
		IPage<ElevatorRescueLogVO> singleRescueLog = baseMapper.getSingleRescueLog(page, elevatorId, beginTime, endTime);
		List<ElevatorRescueLogVO> records = singleRescueLog.getRecords();
		for (ElevatorRescueLogVO record : records) {
			record.setTrapTypeDesc(
				Func.isNull(record.getTrapType()) ? "无记录" :
				new Integer("1").equals(record.getTrapType()) ? "伤人" : "困人"
			);
		}
		singleRescueLog.setRecords(records);

		// 2. 返回数据
		return singleRescueLog;
	}
}
